﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using System.Configuration;

public partial class Despacho : PageBase
{

    #region DespachoDataTableCache
    private DataTable DespachoDataTableCache
    {
        get
        {
            DataTable objTable = null;
            if (Cache["DespachoDataTableCache.aspx" + Session.SessionID] != null)
                objTable = (DataTable)Cache["DespachoDataTableCache.aspx" + Session.SessionID];
            return objTable;
        }
        set
        {
            if (value != null)
            {
                Cache.Insert("DespachoDataTableCache.aspx" + Session.SessionID, value, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
            }
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            cargarEstadosOrdenCargue();
            bindDatosClientes();
        }
        else
        {
            if (DespachoDataTableCache != null)
            {
                ASPxGridViewClientes.DataSource = DespachoDataTableCache;
                ASPxGridViewClientes.DataBind();
            }
        }
    }

    #region cargarEstadosOrdenCargue
    private void cargarEstadosOrdenCargue()
    {
        try
        {
            Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);
            var datos = from a in contexto.AUT_ESTADOS_ORDEN_SALIDAs
                        select a;
            if (datos == null) return;
            ddlEstadosOrden.DataSource = datos;
            ddlEstadosOrden.TextField = "AES_NOMBRE";
            ddlEstadosOrden.ValueField = "AES_ID";
            ddlEstadosOrden.DataBind();
            // ddlDepartamentoOrigen.Items.Insert(0, new DevExpress.Web.ASPxEditors.ListEditItem("--TODOS--", ""));
        }
        catch (Exception)
        {

            throw;
        }
    }
    #endregion


    #region bindDatosClientes
    private void bindDatosClientes()
    {
        try
        {
            #region Filrta el grid con por usuario
            Model.DataClassesAutosolDataContext contexto = new Model.DataClassesAutosolDataContext(ConfigurationManager.AppSettings["Conn"]);
            var datos = from a in contexto.AUT_CLIENTEs
                         join d in contexto.BAS_ZONAS_GEOGRAFICAs on a.ZON_ID equals d.ZON_ID
                            //join e in contexto.BAS_ZONAS_GEOGRAFICA1s on d.ZON_PADRE_ID equals e.ZON_ID

                        //where
                        //    e.TEA_AREA_ID == Convert.ToInt32(ConfigurationManager.AppSettings["AREA_ID"].ToString())
                        select new
                        {
                            a.ACL_ID,
                            a.ACL_DIRECCION,
                            a.ACL_RAZON_SOCIAL,
                            a.ACL_TELEFONO,
                            a.ACL_NIT,
                            CIUDAD = d.ZON_NOMBRE
                            //DEPARTAMENTO = ""
                        };

            if (datos == null) return;
            ASPxGridViewClientes.BeginUpdate();
            ASPxGridViewClientes.DataSource = datos;// objProductosComercialesRendimientosData.DefaultView;
            ASPxGridViewClientes.DataBind();
            ASPxGridViewClientes.EndUpdate();
            DespachoDataTableCache = GetDataView(ASPxGridViewClientes);
            #endregion
            
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            //throw;
        }
    }
    #endregion

    #region GetDataView
    private DataTable GetDataView(ASPxGridView grid)
    {
        DataTable dt = new DataTable();
        foreach (GridViewColumn col in grid.VisibleColumns)
        {
            GridViewDataColumn dataColumn = col as GridViewDataColumn;
            if (dataColumn == null) continue;
            dt.Columns.Add(dataColumn.FieldName);
        }
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            DataRow row = dt.Rows.Add();
            foreach (DataColumn col in dt.Columns)
                row[col.ColumnName] = grid.GetRowValues(i, col.ColumnName);
        }
        return dt;
    }
    #endregion

    protected void btnGenerarReporte_Click(object sender, EventArgs e)
    {
        //Pasar las tres variable para el reporte
        Session["ESTADO"] = ddlEstadosOrden.Value.ToString();
        Session["FECHA_INICIAL"] = txtFechaInicio.Text;
        Session["FECHA_FINAL"] = txtFechaFinal.Text;
        string strCadenaClientes = "";
        List<object> keyValues = ASPxGridViewClientes.GetSelectedFieldValues("AOS_ID");
        try
        {
            foreach (object key in keyValues)
            {
                if (strCadenaClientes == "")
                    strCadenaClientes = key.ToString();
                else
                    strCadenaClientes = strCadenaClientes + "," + key.ToString();
            }
            Session["CLIENTES"] = strCadenaClientes;

            System.Text.StringBuilder l_msg = new System.Text.StringBuilder();
            //TODO: Revisar esta impresión.
            l_msg.Append(@"<script language=javascript>");
            l_msg.Append(@"window.open('DespachoReporte.aspx" + @"', 'VentanaImpresion','location=0, status=0, directories=0, width=800, height=600, resizable=no, hotkeys=no, scrollbars=yes, toolbar=no, menubar=no, personalbar=no');</script>");
            Response.Write(l_msg.ToString());

            //Response.Redirect("EntidadesAdministracion.aspx", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }

    }
}